package com.barbeque.mall.config.realm;

import com.barbeque.mall.bean.user.MarketUser;
import com.barbeque.mall.bean.user.MarketUserExample;
import com.barbeque.mall.mapper.MarketUserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Euphonium
 * @since 2022/07/21
 */
@Component
public class WxRealm extends AuthorizingRealm {

    @Autowired
    MarketUserMapper marketUserMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        MarketUserExample example = new MarketUserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<MarketUser> marketUsers = marketUserMapper.selectByExample(example);
        if (marketUsers.size() == 1) {
            MarketUser marketUser = marketUsers.get(0);
            return new SimpleAuthenticationInfo(marketUser, marketUser.getPassword(), getName());
        }
        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
